import { app, BrowserWindow, ipcMain } from 'electron'
import path, { join } from 'path'
import { handleGetPro, handleGetDatas, handleSetDatas, handleSetting, handleGetStorage } from './handle'

let mainWin: BrowserWindow | null = null
const createWindow = () => {
    mainWin = new BrowserWindow({
        title: 'Main window',
        height: 600, 
        width: 900,
        frame: false,
        resizable: false,
        transparent: true,
        hasShadow: false,
        // 控制窗口显示
        show: false,
        icon: "./favicon/workTodos.png",
        webPreferences: {
            // 调试工具
            devTools: process.env.NODE_ENV === 'development' ? true : false, 
            preload: join(__dirname, '../preload/preload.js')
        },
    })
    // 关闭跨域警告
    process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
    // 未防止窗口显示出来而文本未显示
    // You can use `process.env.VITE_DEV_SERVER_URL` when the vite command is called `serve`
    if (process.env.VITE_DEV_SERVER_URL) {
        mainWin.loadURL(process.env.VITE_DEV_SERVER_URL)
    } else {
        // Load your file
        mainWin.loadFile('dist/index.html');
    }
    // 打开开发工具 devTools: true 时才能打开
    if(process.env.NODE_ENV === 'development') {
        mainWin.webContents.openDevTools()
    }
    mainWin.on('ready-to-show', () => {
        mainWin?.show();
    })
    mainWin.webContents.on('did-finish-load', () => {
        mainWin?.webContents.send('on-app-ready')
    })
}

const handleClose = (event, title) => {
    mainWin?.close();
}
const handleMinimize = (event, title) => {
    mainWin?.minimize();
}
const handleMaximize = (event, title) => {
    if(!mainWin?.isMaximized()){
        mainWin?.maximize();
    }
    else{
        mainWin?.restore();
    }
    return mainWin?.isMaximized();
}


app.whenReady().then(async() => {
    // 设置自动启动
    ipcMain.on('on-setting', handleSetting);
    // 注册事件
    // 项目版本和名称
    ipcMain.handle('on-get-project', handleGetPro)
    ipcMain.on('on-close', handleClose)
    ipcMain.on('on-minimize', handleMinimize)
    ipcMain.handle('on-maximize', handleMaximize)
    // 读取文件
    ipcMain.handle('on-get-datas', handleGetDatas)
    // 写入文件
    ipcMain.handle('on-set-datas', handleSetDatas)
    ipcMain.handle('on-get-storage', handleGetStorage)
    // 创建窗口
    createWindow()
})
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
